<template>
  <!-- 视频AI模块 -->
  <div class="aicloudvideo-detail-model">
    <!-- 标题 -->
    <div class="page-title-wrap">
      <p class="page-title-name">
        <i class="iconfont icon_biaotijiantou" @click="$Ctl.backProvePage()"></i>
        <span class="page-title-text">AI云视</span>
      </p>
    </div>
    <!-- 自动切换开关 -->
    <div class="switch-model">
      <el-switch v-model="switchState" active-color="#0F4286" inactive-color="#3E475D" @change="changeSwitch"></el-switch>
      <p class="switch-text">自动切换</p>
    </div>
    <!-- 单位筛选框 -->
    <div class="search-unit-model">
      <el-select v-model="orgIds" filterable slot="prepend" placeholder="请选择单位" @change="getTypeData(false)">
        <el-option v-if="isMuilUnitUser" label="所有单位" :value="$store.state.userInfo.organizationIds"></el-option>
        <el-option v-for="item in orgList" :label="item.orgName" :value="item.orgId.toString()" :key="item.orgId"></el-option>
      </el-select>
    </div>
    <!-- 时间搜索 -->
    <div class="search-time-model">
      <el-date-picker
        v-model="searchTime"
        type="daterange"
        @change="getTypeData(false)"
        :clearable="false"
        range-separator="—"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="yyyy-MM-dd"
      ></el-date-picker>
    </div>
    <!-- 分页时，第二页的类型 -->
    <div class="header-type-list-model" v-show="pageType == 2">
      <div
        v-for="(item, i) in typeListData"
        class="header-type-item"
        :class="{ active: currentTypeId === item.alarmTypeId }"
        :key="'type_' + i"
        @click="changeType(i)"
      >{{ item.alarmTypeName }}</div>
    </div>
    <div class="aicloudvideo-main-content">
      <!-- 切换视图 -->
      <div class="change-page-btn iconfont" @click="changePage"></div>
      <div class="page-one" v-show="pageType == 1">
        <center-canvas
          class="page-one-item"
          :typeListData="typeListData"
          :currentTypeId="currentTypeId"
          :currentTypeName="currentTypeName"
          @changeType="changeType"
          @stopInterval="changeSwitch"
          ref="centerCanvas"
        ></center-canvas>
        <alarm-capture class="page-one-item" ref="alarmCapture" :onPreview="onPreview"></alarm-capture>
      </div>
      <div class="page-two" v-show="pageType == 2">
        <div class="page-left-wrap">
          <alarm-time-distribute
            :class="{ 'full-height':!showHotWords }"
            class="page-two-item"
            ref="alarmTimeDistribute"
          ></alarm-time-distribute>
          <hot-words v-if="showHotWords" class="page-two-item" ref="hotWords"></hot-words>
        </div>
        <div class="page-right-wrap">
          <duty-hours-statistic class="page-two-item" ref="dutyHoursStatistic" :currentTypeName="currentTypeName"></duty-hours-statistic>
          <alarm-law class="page-two-item" ref="alarmLaw"></alarm-law>
        </div>
      </div>
    </div>
    <trans-ai-pic v-if="showCanvasPreview" :transAiPicToBase64="transAiPicToBase64" :drawData="drawData"></trans-ai-pic>
    <span
      v-show="showPicStatus"
      class="status-tag alarm"
      :class="{ 'is-active':currentStatus==1 }"
      @click="togglePicStatus(1)"
    >报警图片</span>
    <span
      v-show="showPicStatus"
      class="status-tag normal"
      :class="{ 'is-active':currentStatus==2 }"
      @click="togglePicStatus(2)"
    >复位图片</span>
    <el-image-viewer
      v-if="showViewer"
      :on-close="closeViewer"
      :url-list="srcList"
      :on-switch="switchPic"
      :appendToBody="false"
    ></el-image-viewer>
  </div>
</template>
<script>
import { getAIMonitorTypes } from '@/api/record'
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
import utils from '@/utils/util'
import CenterCanvas from './PageModel/CenterCanvas' // 中间画布
import AlarmCapture from './PageModel/AlarmCapture' // 报警抓拍
import AlarmTimeDistribute from './PageModel/AlarmTimeDistribute' // 报警时间点分布
import HotWords from './PageModel/HotWords' // 热词
import DutyHoursStatistic from './PageModel/DutyHoursStatistic' // 值守时长统计
import AlarmLaw from './PageModel/AlarmLaw' // 报警规律
import TransAiPic from '@/components/TransAiPic' // 视频分析图片转base64

export default {
  name: 'AICloudVideo',
  components: {
    CenterCanvas,
    AlarmCapture,
    AlarmTimeDistribute,
    HotWords,
    DutyHoursStatistic,
    AlarmLaw,
    ElImageViewer,
    TransAiPic,
  },
  data() {
    return {
      switchState: false, // 自动切换开关，默认不打开
      needPage: true,
      pageType: 1, // 显示类型
      typeListData: [], // 类型数据
      currentTypeIndex: 0, // 当前类别序号
      currentTypeId: '', // 当前类别ID
      currentTypeName: '', // 当前类别名称
      searchTime: [
        utils.ilinkTimeformat.hoursAgo(24 * 30, 'yyyy-MM-dd'),
        utils.ilinkTimeformat.format(new Date(), 'yyyy-MM-dd'),
      ], // 搜索的时间范围
      orgIds: (this.parames
        ? this.parames.orgId
        : this.$store.state.userInfo.organizationIds
      ).toString(),
      /* 图片预览相关的变量 */
      showViewer: false,
      originList: [], // 原始数据
      srcList: [],
      viewerIndex: 0, // 正在预览哪张图片
      drawData: {}, // 图片对象
      showCanvasPreview: false, // 图片对象转base64的组件
      showPicStatus: false,
      currentStatus: 1,
      showHotWords: this.bsConfig.showVideoHotWords !== false,
      isMuilUnitUser: this.$store.state.userInfo.isMuilUnitUser, //0:单单位用户;1:多单位用户
      orgList: this.$store.state.orgList,
    }
  },
  props: {
    parames: {
      default() {
        return false
      },
    },
  },
  created() {
    this.base64Map = {}
    window.AICloudVideoSwitchInterval &&
      clearInterval(window.AICloudVideoSwitchInterval)
    this.getTypeData()
  },
  methods: {
    // 获取类型数据
    getTypeData(isInit = true) {
      let that = this
      getAIMonitorTypes({
        orgIds: this.orgIds,
      }).then((res) => {
        if (res.status === 200) {
          that.typeListData = res.data
          if (res.data.length == 0) {
            that.currentTypeId = ''
            that.currentTypeName = ''
            that.currentTypeIndex = 0
          } else if (
            isInit ||
            res.data.filter((n) => {
              return n.alarmTypeId == that.currentTypeId
            }).length == 0
          ) {
            that.currentTypeId = res.data[0].alarmTypeId
            that.currentTypeName = res.data[0].alarmTypeName
            that.currentTypeIndex = 0
          }
          that.$nextTick(() => {
            // 首次加载
            that.reloadEchartData()

            that.switchState && that.setAICloudVideoSwitchInterval()
          })
        }
      })
    },
    // 页面展示切换（1920分辨率使用）
    changePage() {
      this.pageType = this.pageType == 1 ? 2 : 1
    },
    // 自动切换开关
    changeSwitch(val) {
      let that = this
      if (val) {
        that.setAICloudVideoSwitchInterval()
      } else {
        window.AICloudVideoSwitchInterval &&
          clearInterval(window.AICloudVideoSwitchInterval)
      }
    },
    // 设置定时器
    setAICloudVideoSwitchInterval() {
      let that = this
      window.AICloudVideoSwitchInterval &&
        clearInterval(window.AICloudVideoSwitchInterval)
      window.AICloudVideoSwitchInterval = setInterval(() => {
        if (that.currentTypeIndex === that.typeListData.length - 1) {
          that.currentTypeIndex = 0
        } else {
          that.currentTypeIndex += 1
        }
        that.currentTypeId =
          that.typeListData[that.currentTypeIndex].alarmTypeId
        that.currentTypeName =
          that.typeListData[that.currentTypeIndex].alarmTypeName
        that.reloadEchartData()
      }, 100000)
    },
    // 切换类型刷新统计图表
    reloadEchartData() {
      let that = this
      that.$Ctl.loading(1, 2000)
      let parames = {
        orgIds: this.orgIds,
        alarmType: that.currentTypeId,
        startTime:
          that.searchTime && that.searchTime.length > 0
            ? that.searchTime[0] + ' 00:00:00'
            : '',
        endTime:
          that.searchTime && that.searchTime.length > 0
            ? that.searchTime[1] + ' 23:59:59'
            : '',
      }
      that.$refs['alarmCapture'].getData(parames)
      that.$refs['alarmTimeDistribute'].getData(parames)
      if (this.showHotWords) that.$refs['hotWords'].getData(parames)
      that.$refs['dutyHoursStatistic'].getData(parames)
      that.$refs['alarmLaw'].getData(parames)
    },
    // 主动切换类型
    changeType(index) {
      let that = this
      if (typeof index === 'number' && index != that.currentTypeIndex) {
        that.currentTypeIndex = index
        that.currentTypeId = that.typeListData[index].alarmTypeId
        that.currentTypeName = that.typeListData[index].alarmTypeName
        that.reloadEchartData()
      }
    },
    onPreview(picObjData, arr) {
      let copyArr = [...arr] // 防止操作数组改变原数组
      let newArr = copyArr.map((element) => {
        return element.picAlarm
      })
      const spliceLength = newArr.indexOf(picObjData.picAlarm)
      this.srcList = newArr.concat(newArr.splice(0, spliceLength))
      this.originList = copyArr.concat(copyArr.splice(0, spliceLength))
      this.switchPic(0)
    },
    switchPic(index, resetStatus = true) {
      this.viewerIndex = index
      let picObjData = this.originList[index]
      if (resetStatus) {
        this.currentStatus = 1
        this.srcList[index] =
          (this.base64Map[picObjData.picAlarm] || picObjData.picAlarm) + ''
      }
      let currentPic = this.srcList[index]
      picObjData.resultRegion =
        this.currentStatus == 1
          ? picObjData.resultRegionAlarm
          : picObjData.resultRegionReset
      this.picObjData = picObjData
      // 需要转码成Base64的
      if (
        !currentPic.startsWith('data:image/') &&
        ((this.currentStatus == 1 && picObjData.resultRegionAlarm) ||
          (this.currentStatus == 2 && picObjData.resultRegionReset))
      ) {
        this.$Ctl.loading(1, 5000)
        this.drawData = picObjData
        this.showCanvasPreview = true
      } else {
        // 图片已经是Base64或者无需画框
        this.$set(this.srcList, this.viewerIndex, currentPic)
      }
      this.showViewer = true
      this.$nextTick(() => {
        // 没有复位图片不显示切换按钮
        this.showPicStatus = !!picObjData.picReset
      })
    },
    togglePicStatus(status) {
      this.currentStatus = status
      if (status == 1) {
        this.srcList[this.viewerIndex] =
          (this.base64Map[this.picObjData.picAlarm] ||
            this.picObjData.picAlarm) + ''
      } else {
        this.srcList[this.viewerIndex] =
          (this.base64Map[this.picObjData.picReset] ||
            this.picObjData.picReset) + ''
      }
      this.switchPic(this.viewerIndex, false)
    },
    closeViewer() {
      this.showViewer = false
      this.showPicStatus = false
      this.showCanvasPreview = false
    },
    transAiPicToBase64(base64Data) {
      this.showCanvasPreview = false
      this.$set(this.srcList, this.viewerIndex, base64Data)
      //   缓存画框后的图片
      this.base64Map[
        this.currentStatus == 1
          ? this.picObjData.picAlarm
          : this.picObjData.picReset
      ] = base64Data
      this.$Ctl.loading(0)
    },
  },
}
</script>
<style lang="scss">
.aicloudvideo-detail-model {
  position: relative;
  padding: 0 0 80px 0;
  width: 100%;
  height: 100%;
  background-color: #061723;
  .page-title-wrap {
    padding: 0 30px;
  }
  .switch-model {
    position: absolute;
    top: 35px;
    left: 280px;
    display: flex;
    align-items: center;
    color: rgba(255, 255, 255, 0.5);
    .switch-text {
      margin-left: 10px;
      font-size: 18px;
    }
  }
  .search-time-model {
    position: absolute;
    top: 25px;
    right: 100px;
    z-index: 2;
  }
  .search-unit-model {
    position: absolute;
    top: 25px;
    right: 480px;
    z-index: 2;
  }
  .header-type-list-model {
    position: absolute;
    top: 15px;
    left: 23%;
    width: 38%;
    height: 75px;
    display: flex;
    overflow-x: scroll;
    .header-type-item {
      margin: 0 5px;
      min-width: 158px;
      height: 60px;
      line-height: 60px;
      background: rgba(6, 23, 35, 1);
      border: 1px solid rgba(100, 184, 255, 1);
      border-radius: 4px;
      box-shadow: inset 0px 0px 15px 1px #64b8ff;
      font-size: 18px;
      color: #52a5ff;
      text-align: center;
      cursor: pointer;
      &.active {
        color: #52dbf1;
        border-color: #64b8ff;
        box-shadow: inset 0px 0px 15px 1px #52dbf1;
      }
    }
  }
  .aicloudvideo-main-content {
    position: relative;
    width: 100%;
    height: calc(100% - 90px);
    .change-page-btn {
      position: absolute;
      top: -69px;
      right: 30px;
      z-index: 10;
      background: url(../../../../assets/images/detailPage/change-page-btn.png)
        center center no-repeat;
      background-size: cover;
      &:hover {
        background: url(../../../../assets/images/detailPage/change-page-btn-hover.png)
          center center no-repeat;
        background-size: cover;
      }
    }
    .page-one {
      position: relative;
      padding: 0 30px;
      width: 100%;
      height: 100%;
      background: url(../../../../assets/images/detailPage/aicloudvideo-bg.png)
        center center no-repeat;
      background-size: cover;
      .page-one-item {
        width: 100%;
        &:first-child {
          height: calc(100% - 215px);
        }
        &:last-child {
          height: 215px;
        }
      }
    }
    .page-two {
      display: flex;
      justify-content: space-between;
      padding: 0 30px;
      width: 100%;
      height: 100%;
      .page-left-wrap,
      .page-right-wrap {
        width: calc(50% - 10px);
        height: 100%;
        .page-two-item {
          margin-bottom: 20px;
          border: 1px solid rgba(47, 181, 254, 0.6);
          padding: 25px;
          height: calc(50% - 10px);
          width: 100%;
          background: rgba(6, 23, 35, 0.7);
          &.full-height {
            height: 100%;
          }
          &:last-child {
            margin-bottom: 0;
          }
          .page-item-title {
            font-size: 28px;
            font-weight: 600;
            color: rgba(81, 128, 206, 1);
            line-height: 40px;
            background: linear-gradient(
              0deg,
              rgba(99, 189, 241, 1) 0%,
              rgba(70, 153, 255, 1) 100%
            );
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
          }
        }
      }
    }
  }
  .status-tag {
    display: inline-block;
    position: fixed;
    top: 40px;
    left: 50%;
    margin-left: -131px;
    border: 1px solid rgba(255, 255, 255, 0.4);
    border-radius: 2px;
    color: rgba(255, 255, 255, 0.5);
    font-size: 16px;
    padding: 8px 25px;
    cursor: pointer;
    z-index: 2999;
    &.normal {
      top: 40px;
      margin-left: 15px;
    }
    &.is-active {
      &.normal {
        color: #1ab46c;
        border-color: #1ab46c;
      }
      &.alarm {
        color: #ce334f;
        border-color: #ce334f;
      }
    }
  }
  .el-image-viewer__img {
    width: 1500px !important;
    max-width: 1500px !important;
  }
}

@media screen and (min-width: 2560px) {
  .aicloudvideo-detail-model {
    .switch-model {
      top: 95px;
      left: 70%;
      z-index: 10;
    }
    .search-time-model {
      left: 270px;
      right: initial;
    }
    .search-unit-model {
      left: 640px;
      right: initial;
    }
    .header-type-list-model {
      display: none !important;
    }
    .aicloudvideo-main-content {
      .change-page-btn {
        display: none;
      }
      .page-one {
        display: block !important;
        position: absolute;
        top: -90px;
        left: 25%;
        padding-top: 20px;
        width: 50%;
        height: calc(100% + 90px);
      }
      .page-two {
        display: flex !important;
        .page-left-wrap,
        .page-right-wrap {
          width: calc(25% - 15px);
        }
      }
    }
  }
}
</style>
